package com.ruoyi.web.controller.system;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.MemberCarConstants;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.ParkingApiUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.service.ICarLogService;
import com.ruoyi.system.service.IInfoLogService;
import com.ruoyi.system.service.IMemberCarService;
import com.ruoyi.system.service.IParkConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/park")
public class ParkController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);


    @Autowired
    private ICarLogService carLogService;


//    @Autowired
//    private MemberService memberService;

    @Autowired
    private IMemberCarService carService;

    @Autowired
    private IParkConfigService parkConfigService;

    @Autowired
    private ParkingApiUtil parkingApiUtil;

    @Autowired
    private IInfoLogService infoLogService;

    @Autowired
    private IMemberCarService memberCarService;

    /**
     *
     * 先判断车辆是否有入场且未出场的日志，
     * 未入场
     * 已入场：会员、非会员
     *
     */

    @PostMapping("/judgeParkInNotLog")
    @Transactional
    public AjaxResult judgeParkInNotLog(@RequestBody MemberCar requestCar) {
        // 记录并校验请求参数
        if (validateRequest(requestCar) != null) {
            return validateRequest(requestCar);
        }

        try {
            // 查询车辆入场日志
            CarLog carLog = carLogService.selectCarLogByCarSn(requestCar.getCarNum());
            log.info("【判断车辆入场状态】根据车牌号 {} 查询到车辆日志: {}", requestCar.getCarNum(), carLog);

            // 处理无入场记录情况
            if (carLog == null) {
                return handleNoEntryRecord(requestCar.getCarNum());
            }

            // 查询车辆信息，是否为会员车辆、在会员车辆库或者临时库
            MemberCar carInfo = carService.findByCarNum(requestCar.getCarNum());
            if (carInfo != null) {
//                在会员车辆库或者临时车辆库中，进场时已经推过优惠
                return AjaxResult.success("是会员车辆");

            }
            return AjaxResult.success("非会员车辆");

        } catch (Exception e) {
            return handleException(requestCar.getCarNum(), e);
        }
    }



    /**
     * 判断车辆是否有入场且未出场的日志，是否打折了
     * 判断车辆是否被绑定，若未绑定则执行绑定并推送优惠
     */

    @PostMapping("/judgeParkIn")
    @Transactional
    public AjaxResult judgeParkIn(@RequestBody MemberCar requestCar) {
        // 记录并校验请求参数
        if (validateRequest(requestCar) != null) {
            return validateRequest(requestCar);
        }

        try {
            // 查询车辆入场日志
            CarLog carLog = carLogService.selectCarLogByCarSn(requestCar.getCarNum());
            log.info("【判断车辆入场状态】根据车牌号 {} 查询到车辆日志: {}", requestCar.getCarNum(), carLog);

            // 处理无入场记录情况
            if (carLog == null) {
                return handleNoEntryRecord(requestCar.getCarNum());
            }

            // 查询车牌绑定状态
            MemberCar dbCar = queryMemberCarInfo(requestCar, carLog);

            // 处理未绑定情况
            if (dbCar == null) {
                return handleUnboundCar(requestCar, 0);
            }

            // 解析绑定状态
            Integer carStatus = dbCar.getCarStatus();
            String dbOpenid = dbCar.getOpenid();
            String dbPhone = dbCar.getMemberPhone();
            log.info("【判断车辆入场状态】车牌 {} 绑定状态: {}, 绑定OpenID: {}, 绑定手机号: {}",
                    requestCar.getCarNum(), carStatus, dbOpenid, dbPhone);

            // 处理已绑定且是当前用户的情况
            if (isBoundByCurrentUser(carStatus, requestCar, dbCar)) {
                return success("该车牌已被您绑定并享受过优惠");
            }

            // 处理已绑定但非当前用户的情况
            if (isBoundByOtherUser(carStatus, requestCar, dbCar)) {
                return AjaxResult.error(4001, "车牌已被会员绑定，请登录会员后缴费");
            }

            // 处理已禁用状态
            if (isCarDisabled(carStatus)) {
                return AjaxResult.error(4001, "抱歉，车牌已被禁用，请联系客服！");
            }

            // 处理其他状态
            return handleUnboundCar(requestCar, carStatus);

        } catch (Exception e) {
            return handleException(requestCar.getCarNum(), e);
        }
    }

    // 提取：请求参数校验
    private AjaxResult validateRequest(MemberCar requestCar) {
        if (requestCar == null || StringUtils.isEmpty(requestCar.getCarNum())) {
            log.error("【判断车辆入场状态】车牌号为空，请求参数不合法");
            return error("车牌号不能为空");
        }
        log.info("【判断车辆入场状态】请求参数 - carSn: {}, openid: {}, phone: {}",
                requestCar.getCarNum(), requestCar.getOpenid(), requestCar.getMemberPhone());
        return null;
    }

    // 提取：查询会员车辆信息
    private MemberCar queryMemberCarInfo(MemberCar requestCar, CarLog carLog) {
        MemberCar queryParam = new MemberCar();
        queryParam.setCarNum(carLog.getCarSn());
        queryParam.setMemberPhone(requestCar.getMemberPhone());
        queryParam.setOpenid(requestCar.getOpenid());
        log.info("【判断车辆入场状态】会员车辆查询参数: {}", queryParam);

        return memberCarService.judgeMemberCarInfo(queryParam);
    }

    // 提取：处理无入场记录逻辑
    private AjaxResult handleNoEntryRecord(String carNum) {
        log.info("【判断车辆入场状态】车辆 {} 无入场记录", carNum);
        return success("未找到入场记录");
    }

    // 提取：处理未绑定车辆逻辑
    private AjaxResult handleUnboundCar(MemberCar requestCar, Integer carStatus) {
        log.info("【判断车辆入场状态】车牌 {} 未绑定或状态异常，准备执行绑定操作", requestCar.getCarNum());

        // 1. 查询当前用户已绑定的车辆列表
        List<MemberCar> boundCars = memberCarService.listByMemberCar(requestCar.getMemberPhone());
        log.info("【车辆绑定校验】用户 {} 已绑定车辆数量: {}", requestCar.getMemberPhone(), boundCars.size());

        // 2. 校验绑定数量是否超过限制（最多5辆）
        if (boundCars != null && boundCars.size() >= 5) {
            log.warn("【车辆绑定校验】用户 {} 已绑定 {} 辆车，超过5辆绑定上限",
                    requestCar.getMemberPhone(), boundCars.size());
            return error("最多只能绑定5个车牌，请先解绑！");
        }

        Map<String, Object> result = memberCarService.insertMemberCarOfJudgeParkIn(requestCar, carStatus);
        log.info("【判断车辆入场状态】绑定操作返回结果: {}", result);

        if ((boolean) result.get("success")) {
            return success(result.get("message"));
        } else {
            return error(result.get("message").toString());
        }
    }

    // 提取：判断是否被当前用户绑定
    private boolean isBoundByCurrentUser(Integer carStatus, MemberCar requestCar, MemberCar dbCar) {
        return carStatus == MemberCarConstants.CAR_STATUS_BOUND &&
                (requestCar.getOpenid().equals(dbCar.getOpenid()) ||
                        requestCar.getMemberPhone().equals(dbCar.getMemberPhone()));
    }

    // 提取：判断是否被其他用户绑定
    private boolean isBoundByOtherUser(Integer carStatus, MemberCar requestCar, MemberCar dbCar) {
        return carStatus == MemberCarConstants.CAR_STATUS_BOUND &&
                !(requestCar.getOpenid().equals(dbCar.getOpenid()) ||
                        requestCar.getMemberPhone().equals(dbCar.getMemberPhone()));
    }

    // 提取：判断车辆是否被禁用
    private boolean isCarDisabled(Integer carStatus) {
        return carStatus == MemberCarConstants.CAR_STATUS_DISABLED;
    }

    // 提取：异常处理
    private AjaxResult handleException(String carNum, Exception e) {
        log.error("【判断车辆入场状态】接口执行异常，carSn: {}, 异常信息: {}", carNum, e.getMessage(), e);
        return error("系统异常，请稍后再试");
    }




//    @PostMapping("/judgeParkIn")
//    @Transactional
//    public AjaxResult judgeParkIn(@RequestBody MemberCar memberCar) {
//        // 记录接口入参
//        log.info("【判断车辆入场状态】请求参数 - carSn: {}, openid: {}, phone: {}",
//                memberCar.getCarNum(), memberCar.getOpenid(), memberCar.getMemberPhone());
//
//        // 参数非空校验
//        if (StringUtils.isEmpty(memberCar.getCarNum())) {
//            log.error("【判断车辆入场状态】车牌号为空，请求参数不合法");
//            return error("车牌号不能为空");
//        }
//
//        try {
//            // 查询车辆入场日志
//            CarLog carLog = carLogService.selectCarLogByCarSn(memberCar.getCarNum());
//            log.info("【判断车辆入场状态】根据车牌号 {} 查询到车辆日志: {}", memberCar.getCarNum(), carLog);
//
//            // 判空处理：无入场记录
//            if (carLog == null) {
//                log.info("【判断车辆入场状态】车辆 {} 无入场记录", memberCar.getCarNum());
//                return success("未找到入场记录");
//            }
//
//            // 提取日志关键信息
//            Integer discountStatus = carLog.getDiscountStatus();
//            log.info("【判断车辆入场状态】车辆 {} 折扣状态: {}", memberCar.getCarNum(), discountStatus);
//
//            // 构建会员车辆查询参数
//            MemberCar memberCarQuery = new MemberCar();
//            memberCarQuery.setCarNum(carLog.getCarSn());
//            memberCarQuery.setMemberPhone(memberCar.getMemberPhone());
//            memberCarQuery.setOpenid(memberCar.getOpenid());
//            log.info("【判断车辆入场状态】会员车辆查询参数: {}", memberCarQuery);
//
//            // 查询车牌绑定状态
//            MemberCar memberCarInfo = memberCarService.judgeMemberCarInfo(memberCarQuery);
//            log.info("【判断车辆入场状态】车牌 {} 绑定信息: {}", memberCar.getCarNum(), memberCarInfo);
//
//
//            //查不到绑定信息
//            if (memberCarInfo == null) {
//                log.error("【判断车辆入场状态】查询车牌绑定时返回空结果说明未被绑定过，carSn: {}", memberCar.getCarNum());
//                Integer carStatus =0;
//
//                log.info("【判断车辆入场状态】车牌 {} 未绑定或状态异常，准备执行绑定操作", memberCar.getCarNum());
//                // 执行绑定及优惠推送
//                Map<String, Object> result = memberCarService.insertMemberCarOfJudgeParkIn(memberCar, carStatus);
//                log.info("【判断车辆入场状态】绑定操作返回结果: {}", result);
//
//                if ((boolean) result.get("success")) {
//                    log.info("【判断车辆入场状态】车牌 {} 绑定成功，消息: {}", memberCar.getCarNum(), result.get("message"));
//                    return AjaxResult.success(result.get("message"));
//                } else {
//                    log.error("【判断车辆入场状态】车牌 {} 绑定失败，错误信息: {}", memberCar.getCarNum(), result.get("message"));
//                    return AjaxResult.error(result.get("message").toString());
//                }
//
//            }
//
//            // 解析绑定状态
//            Integer carStatus = memberCarInfo.getCarStatus();
//            String openidBy = memberCarInfo.getOpenid();
//            String memberPhone = memberCarInfo.getMemberPhone();
//            log.info("【判断车辆入场状态】车牌 {} 绑定状态: {}, 绑定OpenID: {}, 绑定手机号: {}",
//                    memberCar.getCarNum(), carStatus, openidBy, memberPhone);
//
//            // 处理已绑定且是当前用户的情况
//            if (carStatus == MemberCarConstants.CAR_STATUS_BOUND
//                    && (memberCar.getOpenid().equals(openidBy) || memberCar.getMemberPhone().equals(memberPhone))) {
//                log.info("【判断车辆入场状态】车牌 {} 已被当前用户绑定，且已享受优惠", memberCar.getCarNum());
//                return AjaxResult.success("该车牌已被您绑定并享受过优惠");
//            }
//            // 处理已绑定但非当前用户的情况
//            else if (carStatus == MemberCarConstants.CAR_STATUS_BOUND
//                    && !(memberCar.getOpenid().equals(openidBy)  || memberCar.getMemberPhone().equals(memberPhone))) {
//                log.warn("【判断车辆入场状态】车牌 {} 已被其他用户绑定，当前OpenID: {}, 绑定OpenID: {}",
//                        memberCar.getCarNum(), memberCar.getOpenid(), openidBy);
//                return AjaxResult.error(4001, "车牌已被会员绑定，请登录会员后缴费");
//            }
//            // 处理已禁用状态
//            else if (carStatus == MemberCarConstants.CAR_STATUS_DISABLED) {
//                log.warn("【判断车辆入场状态】车牌 {} 已被禁用", memberCar.getCarNum());
//                return AjaxResult.error(4001, "抱歉，车牌已被禁用，请联系客服！");
//            }
//            // 处理未绑定或其他状态
//            else {
//                log.info("【判断车辆入场状态】车牌 {} 未绑定或状态异常，准备执行绑定操作", memberCar.getCarNum());
//                // 执行绑定及优惠推送
//                Map<String, Object> result = memberCarService.insertMemberCarOfJudgeParkIn(memberCar, carStatus);
//                log.info("【判断车辆入场状态】绑定操作返回结果: {}", result);
//
//                if ((boolean) result.get("success")) {
//                    log.info("【判断车辆入场状态】车牌 {} 绑定成功，消息: {}", memberCar.getCarNum(), result.get("message"));
//                    return AjaxResult.success(result.get("message"));
//                } else {
//                    log.error("【判断车辆入场状态】车牌 {} 绑定失败，错误信息: {}", memberCar.getCarNum(), result.get("message"));
//                    return AjaxResult.error(result.get("message").toString());
//                }
//            }
//        } catch (Exception e) {
//            log.error("【判断车辆入场状态】接口执行异常，carSn: {}, 异常信息: {}", memberCar.getCarNum(), e.getMessage(), e);
//            return error("系统异常，请稍后再试");
//        }
//    }
//

    /**
     * 首页数据列表
     */
    @GetMapping("/index")
    public Map<String, Object> index(
            @RequestParam(required = false, defaultValue = "20") Integer limit,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false) String truename,
            @RequestParam(required = false) String mobile
    ) {
        Map<String, Object> result = new HashMap<>();
        result.put("resCode", 0);
        result.put("resMsg", "成功");
        return result;
    }


    /**
     * 捷顺
     * 车辆进场处理
     */
    @PostMapping("/parkIn/js/dyc")
    public Map<String, Object> parkIn(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", 1);
        result.put("message", "成功");

        try {
            // 获取请求体
            String postInfo = getRequestBody(request);
            logMessage("park/jc_log_" + getCurrentDate() + ".txt",
                    "时间:" + getCurrentDateTime() + ",msg:" + postInfo);

            // 解析JSON
            Map<String, Object> data = JSON.parseObject(postInfo);
            if (data == null || !data.containsKey("dataItems")) {
                result.put("resultCode", 1);
                result.put("message", "获取信息失败");
                return result;
            }

            List<Map<String, Object>> dataItems = JSON.parseObject(
                    data.get("dataItems").toString(),
                    new TypeReference<List<Map<String, Object>>>() {}
            );

            for (Map<String, Object> item : dataItems) {
                // 处理车牌和时间，捷顺车牌需要 -
                String carNumber = item.get("carNumber").toString();
                Date inTime = parseDate(item.get("inTime").toString());
                String parkCode = item.get("parkCode").toString();


//                根据停车场编号，查询web端对这个停车场使用什么规则，按照规则减免多长时间-会员免费停车时长

                // 检查是否已有进场记录
                CarLog logInfo = carLogService.selectCarLogByCarSnAndInTime(carNumber, inTime);


                if (logInfo == null) {

                    //保存车辆进场日志
                    InfoLog infoLogOfIn = new InfoLog();
                    infoLogOfIn.setVehiclePlate(carNumber);

//操作类型：1=进场打折，2=出场，3=通知支付 ，4=车辆已进场且未享受优惠在添加车辆时打折，
// 5=进场，6=查询缴费时添加车辆扯着但推送打折失败，7=添加车辆但推送打折失败
                    infoLogOfIn.setActionType(5);
                    infoLogOfIn.setActionTime(new Date());
                    // 转换为 JSON 字符串
                    infoLogOfIn.setJsonData(JSONUtil.toJsonStr(item));

                    infoLogService.insertInfoLog(infoLogOfIn);



                    // 查询车辆信息，是否为会员车辆、在会员车辆库或者临时库
                    MemberCar carInfo = carService.findByCarNum(carNumber);
                    ParkConfig config = new ParkConfig();
                    config.setParkId(parkCode);

                    //会员车辆，根据车场编号，查询规则
                    if (carInfo != null) {
                        RuleConfig ruleConfig = parkConfigService.selectRuleConfigByParkCode(config);

//                        if (ruleConfig == null) {
//                            logMessage("park/jc_log_" + getCurrentDate() + ".txt",
//                                    "时间:" + getCurrentDateTime() + ",car_sn:" + carNumber + ",msg:无进场减免规则");
//                            // 或继续记录进场但不推送减免
//                            return;
//                        }

                        Integer freeTime = ruleConfig.getMemberFreeMinutes();

//                        if (freeTime == null || freeTime <= 0) {
//                            logMessage("park/jc_log_" + getCurrentDate() + ".txt",
//                                    "时间:" + getCurrentDateTime() + ",car_sn:" + carNumber + ",msg:减免时长配置错误");
//                            return; // 时长无效，跳过推送
//                        }


                        // 从规则配置中获取减免时长（单位：分钟）

//                        会员车辆要推送一个减免时长，捷顺的逻辑是，会员减免时长在规则中定义，分钟
//                        Integer freeTime = 120;


                        Map<String, Object> map =   parkingApiUtil.addMemberRelief(carNumber, parkCode,freeTime);

                        logMessage("park/jc_log_" + getCurrentDate() + ".txt",
                                    "时间:" + getCurrentDateTime() + ",msg:" + map.get("resMsg")+ ",car_sn:" + carNumber + ",msg:会员" );


                        // 记录进场信息
                        CarLog log = new CarLog();
                        log.setTenantId(1);
                        log.setCarId(carInfo.getId());
                        log.setInTime(inTime);
                        log.setMemberId(carInfo.getMemberPhone());
                        log.setCreateTime(new Date());
                        log.setCarSn(carNumber);
//                        出场状态（0=未出场，1=已出场）
                        log.setOutStatus(0);
//                        享受优惠
                        log.setDiscountStatus(1);
//                        进场时打折
                        log.setDiscountWhen("进场时打折");
                        carLogService.insertCarLog(log);

                        logMessage("park/jc_log_" + getCurrentDate() + ".txt",
                                "开始保存进场日志信息：时间:" + getCurrentDateTime() + ",msg:" + map.get("resMsg")+ ",car_sn:" + carNumber + ",msg:会员" );


//                        保存进场打折日志信息
                        // 创建日志对象
                        InfoLog infoLog = new InfoLog();
                        infoLog.setVehiclePlate(carNumber);

//操作类型：1=进场打折，2=出场，3=通知车场已支付 ，4=车辆已进场且未享受优惠在添加车辆时打折，
// 5=进场，6=查询缴费时添加车辆但推送打折失败，7=添加车辆但推送打折失败，8=车辆已进场且未享受优惠在查询交费时添加车辆并打折
                        infoLog.setActionType(1);
                        infoLog.setActionTime(new Date());
                        // 转换为 JSON 字符串
                        infoLog.setJsonData(JSONUtil.toJsonStr( map.get("jsonResult")));

                        int flag = infoLogService.insertInfoLog(infoLog);

                        logMessage("park/jc_log_" + getCurrentDate() + ".txt",
                                "保存的进场日志信息：成功条数:" + flag + ",msg:" +"内容:" + infoLog );

                    } else {

                        CarLog log = new CarLog();
                        log.setTenantId(1);

                        log.setInTime(inTime);
                        log.setCreateTime(new Date());
                        log.setCarSn(carNumber);
//                        出场状态（0=未出场，1=已出场）
                        log.setOutStatus(0);
                        log.setDiscountStatus(0);
                        carLogService.insertCarLog(log);

                        // 没有绑定车牌
                        logMessage("park/jc_log_" + getCurrentDate() + ".txt",
                                "时间:" + getCurrentDateTime() + ",car_sn:" + carNumber + ",msg:非会员");

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("resultCode", 1);
            result.put("message", "处理失败");
        }

        return result;
    }

    /**
     * 捷顺
     * 车辆出场处理
     */
    @PostMapping("/parkOut/js/dyc")
    public Map<String, Object> parkOut(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", 0);
        result.put("message", "成功");

        try {
            // 获取请求体
            String postInfo = getRequestBody(request);
            logMessage("park/cc_log_" + getCurrentDate() + ".txt",
                    "时间:" + getCurrentDateTime() + ",msg:" + postInfo);

            // 解析JSON
            Map<String, Object> data = JSON.parseObject(postInfo);
            if (data == null || !data.containsKey("dataItems")) {
                result.put("resultCode", 1);
                result.put("message", "获取信息失败");

//                记录出场日志--失败情况下的错误信息
                InfoLog infoLog = new InfoLog();

//操作类型：1=进场打折，2=出场，3=通知车场已支付 ，4=车辆已进场且未享受优惠在添加车辆时打折，
// 5=进场，6=查询缴费时添加车辆但推送打折失败，7=添加车辆但推送打折失败，8=车辆已进场且未享受优惠在查询交费时添加车辆并打折
                infoLog.setActionType(2);
                infoLog.setActionTime(new Date());
                // 转换为 JSON 字符串
                infoLog.setJsonData(JSONUtil.toJsonStr(data));
                infoLog.setErrorMessage("获取信息失败");
                infoLogService.insertInfoLog(infoLog);


                return result;
            }

            List<Map<String, Object>> dataItems = JSON.parseObject(
                    data.get("dataItems").toString(),
                    new TypeReference<List<Map<String, Object>>>() {}
            );


            for (Map<String, Object> item : dataItems) {
                // 处理车牌和时间
                String carNumber = item.get("carNumber").toString();
                Date inTime = parseDate(item.get("inTime").toString());
                Date outTime = parseDate(item.get("outTime").toString());


                // 记录每一条出场日志

                // 创建日志对象
                InfoLog infoLog = new InfoLog();

//操作类型：1=进场打折，2=出场，3=通知车场已支付 ，4=车辆已进场且未享受优惠在添加车辆时打折，
// 5=进场，6=查询缴费时添加车辆但推送打折失败，7=添加车辆但推送打折失败，8=车辆已进场且未享受优惠在查询交费时添加车辆并打折
                infoLog.setActionType(2);
                infoLog.setActionTime(new Date());
                // 转换为 JSON 字符串
                infoLog.setJsonData(JSONUtil.toJsonStr(item));
                infoLogService.insertInfoLog(infoLog);


                // 更新出场信息
                if (outTime != null) {
                    carLogService.updateCarLogOutTime(carNumber, inTime, outTime, 1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("resultCode", 1);
            result.put("message", "处理失败");
        }

        return result;
    }

    // 辅助方法：获取请求体
    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    // 辅助方法：记录日志
    private void logMessage(String filePath, String message) {
        try {
            // 实际项目中应该使用日志框架如Logback
            System.out.println(message);
            // FileUtils.writeStringToFile(new File(filePath), message + "\r\n", true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 辅助方法：获取当前日期
    private String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }

    // 辅助方法：获取当前日期时间
    private String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    // 辅助方法：解析日期
    private Date parseDate(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return new Date();
        }
    }


}
